<template>
  <div>
    <bread :List="breadList" ref="bread"></bread>
    <el-card class="box-card">
<!--      搜索框-->
      <div>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-input placeholder="请输入内容"  class="input-with-select" v-model="queryInfo.query" clearable @clear="getUserList">
              <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="dialogFormVisible = true">添加用户</el-button>
<!--          添加用户-->
            <el-dialog title="添加用户" :visible.sync="dialogFormVisible" @close="addUserClear">
              <el-form :rules="rules" :model="addUser" ref="addUserRef">
                <el-form-item label="用户名" prop="username">
                  <el-input  v-model="addUser.username" ></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input v-model="addUser.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input  v-model="addUser.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                  <el-input v-model="addUser.mobile"></el-input>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUserList">确 定</el-button>
              </div>
            </el-dialog>
          </el-col >
        </el-row>
      </div>
<!--      用户列表-->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作"  width="180px">
          <template v-slot="scope">
         <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditForm(scope.row.id)"></el-button>
         <el-button type="danger" icon="el-icon-delete" size="mini" @click="delUserForm(scope.row.id)"></el-button>
          <el-tooltip placement="top" content="分配角色" :enterable="false">
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showAddRoles(scope.row)">
            </el-button>
          </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
<!--      分页-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1,2,5,10]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
<!--     修改用户-->
      <el-dialog
          title="修改用户信息"
          :visible.sync="editFormVisible"
          width="50%" @close="editDialogClose">
        <el-form :rules="rules" :model="editFrom" ref="editUserRef">
          <el-form-item label="用户名">
            <el-input  v-model="editFrom.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input  v-model="editFrom.email" ></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input  v-model="editFrom.mobile" ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
         <el-button @click="editFormVisible = false">取 消</el-button>
         <el-button type="primary" @click="addEditUser">确 定</el-button>
        </span>
      </el-dialog>
<!--      分配角色-->
      <el-dialog
           title="分配角色"
           :visible.sync="addRolesDialog"
           width="50%">
        <el-form>
          <el-form-item label="当前用户：">{{ addRolesForm.username}}</el-form-item>
          <el-form-item label="当前角色：">{{ addRolesForm.role_name}}</el-form-item>
          <el-form-item label="分配角色：">
            <el-select  placeholder="请选择角色" v-model="role">
              <el-option v-for="item in RolesForm" :label="item.roleName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
         <el-button @click="addRolesDialog = false">取 消</el-button>
         <el-button type="primary" @click="addRoles(role)">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import bread from "@/components/bread";
export default {
  name: "users",
  components: {bread},
  data(){
    return{
      queryInfo:{
        query: '',
        pagenum: 1,
        pagesize:5
      },
      userList:[],
      breadList:[],
      total:0,
      dialogFormVisible:false,
      editFormVisible:false,
      addRolesDialog:false,
      editFrom:{},
      addRolesForm:{},
      RolesForm:[],
      role:'',
      addUser:{
        username:'',
        password:'',
        email:'',
        mobile:'',
      },
      rules:{
      username:[
          { required:true ,message:'请输入用户名' ,trigger: 'blur' },
          { min:3 , max:10 ,message: '用户名在3-10位', trigger: 'blur'}],
      password:[
        {required: true ,message:'请输入密码' ,trigger: 'blur' },
        { min:6 , max:15 ,message:'密码在6-15位', trigger: 'blur'}
      ],
      email: [
        {required: true ,message:'请输入邮箱' ,trigger: 'blur' },
      ],
      mobile: [
        {required: true ,message:'请输入手机号' ,trigger: 'blur' },
      ]
      },
    }
  },
  async created() {
    this.getUserList()
    const { data: res } = await this.$http.get('menus')
    this.breadList.push(res.data[0].authName)
    this.breadList.push(res.data[0].children[0].authName)
    this.$refs.bread.getBreadList(this.breadList)
  },
  methods:{
   async getUserList(){
      const { data:res} = await this.$http.get('users',{params:this.queryInfo});
      console.log(res)
     if(res.meta.status !==200){
       return this.$message.error("获取用户列表失败")
     }
     this.userList=res.data.users
     this.total=res.data.total
    },
    handleSizeChange(newSize){
      this.queryInfo.pagesize=newSize
      this.getUserList()

    },
    handleCurrentChange(newPage){
     this.queryInfo.pagenum=newPage
      this.getUserList()
    },
    //监听状态的改变
    async userStateChange(userInfo){
      console.log(userInfo)
      const {data:res} = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status ===200){
        return this.$message.success("状态更新成功！")
      }
      else {
        this.$message.error("状态更新失败！")
      }
    },
    // 添加用户
     addUserList(){
      this.$refs.addUserRef.validate( async valid =>{
        if(!valid)return
        const { data:res } =await this.$http.post('users',this.addUser)
        console.log( res )
        if (res.meta.status ===201){
          this.$message.success(res.meta.msg)
          this.getUserList()
        }
        else {
          this.$message.error(res.meta.msg)
        }
        this.dialogFormVisible=false
      })
    },
    //  对话框关闭
    addUserClear(){
     this.$refs.addUserRef.resetFields()
     },
    editDialogClose(){
     this.$refs.editUserRef.resetFields()
    },
    //展示修改的对话框
   async showEditForm(id){
     this.editFormVisible=true
     const{ data:res } = await this.$http.get('users/'+id)
     if ( res.meta.status !== 200){
       return this.$message.error(res.meta.msg)
     }
     this.editFrom = res.data
    },
    //提交修改
     addEditUser(){
     this.$refs.editUserRef.validate(async valid =>{
       if (!valid) return
       const { data:res} = await this.$http.put('users/'+this.editFrom.id,{ email:this.editFrom.email ,mobile:this.editFrom.mobile})
        if (res.meta.status === 200){
          this.$message.success(res.meta.msg)
          this.getUserList()
        }
        else {
          this.$message.error(res.meta.msg)
        }
        this.editFormVisible=false
     })
    },
    //删除用户信息
    async delUserForm(id){
        this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then( async () => {
          const { data:res} = await this.$http.delete(`users/${id}`)
          if (res.meta.status ===200){
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getUserList()
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    //添加角色
   async addRoles(id){
     const { data:res} =await this.$http.put('users/'+this.addRolesForm.id+'/role',{ rid:id})
     if (res.meta.status ===200){
       this.$message.success(res.meta.msg)
     }
     else {
       this.$message.error(res.meta.msg)
     }
     this.addRolesDialog=false
     this.getUserList()
    },
    //展示分配角色的对话框
    async showAddRoles(user){
     this.addRolesDialog=true
      this.addRolesForm=user
    const { data:res}= await this.$http.get('roles')
      this.RolesForm=res.data
      console.log(this.RolesForm)
    }
    }
}
</script>
<style scoped>
.el-select .el-input {
  width: 130px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
.el-card{
  margin-top: 10px;
}
.el-table{
  margin-top: 20px;
}
.el-pagination{
  margin-top: 20px;
}
</style>
